<template>
  <div>
        <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 商品列表 -->
    <el-card class="box-card">
      <el-button type="primary" @click="showAddCate">添加分类</el-button>
      <!-- 添加分类对话框 -->
      <el-dialog
        title="提示"
        @close="addCateClose"
        :visible.sync="addCateFlag"
        width="50%">
        <el-form ref="addCateRef" :model="addCateForm" :rules="addUserRules" label-width="120px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父类名称">
            <el-cascader
              clearable
              style="width: 100%"
              v-model="cascaderValue"
              :options="cateArr"
              :props="cascaderProps"
              @change="handleChange">
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateFlag = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 树形表格组件 -->
        <tree-table
        border
        show-index
        :show-row-hover="false"
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        :data="cateList"
        :columns="columns"
        class="treeTable">
        <!-- 是否有效 -->
        <template slot-scope="scope" slot="isOk">
          <i v-if="!scope.row.cat_deleted" class="el-icon-success" style="color: green"></i>
          <i v-else class="el-icon-error" style="color: red"></i>
        </template>
        <!-- 等级标签 -->
        <template slot-scope="scope" slot="level">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot-scope="scope" slot="operate">
           <el-button @click="showEditSort(scope.row)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
           <el-button @click="delSort(scope.row.cat_id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
        </template>
        </tree-table>
        <!-- 编辑分页对话框 -->
        <el-dialog
          title="提示"
          :visible.sync="editSortFlag"
          width="50%">
          <el-form ref="editSortForm" :model="editSortInfo" :rules="addUserRules" label-width="80px">
            <el-form-item label="分类名称" prop="cat_name">
              <el-input v-model="editSortInfo.cat_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editSortFlag = false">取 消</el-button>
            <el-button @click="editSort" type="primary">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[5, 8, 10, 30]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取商品分类的参数
      queryData: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 需要渲染的数据
      cateList: [],
      // 数据的总条数
      total: 0,
      // 每一列数据渲染的配置
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', type: 'template', template: 'isOk' },
        { label: '排序', type: 'template', template: 'level' },
        { label: '操作', type: 'template', template: 'operate' }
      ],
      // 添加分类对话框
      addCateFlag: false,
      // 添加分类表单
      addCateForm: {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      },
      // 表单验证规则
      addUserRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      },
      // 二级分类数据
      cateArr: [],
      // 级联选择器选择的数据
      cascaderValue: [],
      // 级联选择器配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true
      },
      // 编辑角色对话框是否显示
      editSortFlag: false,
      // 编辑角色的Id
      editSortId: 0,
      // 编辑用户时每一行的数据
      editSortRow: {},
      // 编辑角色数据
      editSortInfo: {
        cat_name: ''
      }
    }
  },

  created () {
    this.getCateList()
  },

  methods: {
    // 获取商品数据
    async getCateList () {
      const { data: res } = await this.$axios.get('categories', { params: this.queryData })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res.data.result)
      console.log(res.data)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 删除分类
    delSort (id) {
      this.$confirm('此操作将删除该分类, 是否继续?', '删除分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('categories/' + id)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateList()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 条数发生变化
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getCateList()
    },
    // 页码发生变化
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getCateList()
    },
    // 显示添加分类对话框
    showAddCate () {
      this.addCateFlag = true
      this.getCateArr()
    },
    // 获取二级分类
    async getCateArr () {
      const { data: res } = await this.$axios.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.cateArr = res.data
    },
    handleChange (newArr) {
      if (newArr.length === 2) {
        this.addCateForm.cat_level = 2
        this.addCateForm.cat_pid = newArr[newArr.length - 1]
      }
      if (newArr.length === 1) {
        this.addCateForm.cat_level = 1
        this.addCateForm.cat_pid = newArr[newArr.length - 1]
      }
      if (newArr.length === 0) {
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      }
    },
    // 关闭添加分类对话框
    addCateClose () {
      this.$refs.addCateRef.resetFields()
      this.cascaderValue = []
    },
    // 确定添加分类
    async addCate () {
      this.$refs.addCateRef.validate(async flag => {
        console.log(flag)
        if (!flag) return
        const { data: res } = await this.$axios.post('categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addCateFlag = false
        this.getCateList()
      })
    },
    // 显示编辑分类对话框
    showEditSort (row) {
      this.editSortId = row.cat_id
      this.editSortInfo.cat_name = JSON.parse(JSON.stringify(row)).cat_name
      this.editSortFlag = true
    },
    // 确定修改分类
    editSort () {
      this.$refs.editSortForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.editSortId}`, this.editSortInfo)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editSortFlag = false
        this.getCateList()
      })
    }
  }
}
</script>

<style scoped lang='less'>
.treeTable {
  margin: 20px 0;
}
</style>
